package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.impl.MinIOFileTemplate;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.dtos.WmMaterialDto;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.pojos.wemedia.WmMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @Author Lijx
 * @Date 2024-07-21 14:33
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private MinIOFileTemplate minIOFileTemplate;

    /**
     * 分页查询自媒体素材列表
     * @param materialDto
     * @return
     */
    @Override
    public ResponseResult getMaterialPage(WmMaterialDto materialDto) {
        //参数校验
        if (materialDto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        materialDto.checkParam();

        //组装查询条件：wrapper
        //条件一：是否查询收藏
        //条件二:按创建时间倒叙
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.<WmMaterial>lambdaQuery()
                .eq(materialDto.getIsCollection() == 1, WmMaterial::getIsCollection, materialDto.getIsCollection())
                .orderByDesc(WmMaterial::getCreatedTime);

        //构建分页page
        Page<WmMaterial> page = new Page<>(materialDto.getPage(),materialDto.getSize());

        //查询数据
        page(page,wrapper);

        //封装数据返回
        PageResponseResult pageResult = new PageResponseResult(
                (int)page.getCurrent(),
                (int)page.getSize(),
                (int)page.getTotal());
        pageResult.setData(page.getRecords());

        return pageResult;
    }

    /**
     * 上传素材
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult upload(MultipartFile multipartFile) {
        if (multipartFile.getOriginalFilename() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }

        try {
            //生产文件名称
            String originalFilename = multipartFile.getOriginalFilename();
            String str = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uuid = UUID.randomUUID().toString();
            String fileName = uuid + str;

            //将素材文件上传到minio
            String url = minIOFileTemplate.uploadImgFile("", fileName, multipartFile.getInputStream());

            //封装数据
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUrl(url);
            wmMaterial.setType((short)0);
            //从threadLocal中获取用户id
            Integer userId = WmThreadLocalUtil.getUserId();
            wmMaterial.setUserId(userId);
            wmMaterial.setIsCollection((short)0);
            wmMaterial.setCreatedTime(new Date());

            //将minio返回的路径保存到素材数据库中
            save(wmMaterial);

            return ResponseResult.okResult(wmMaterial);
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    /**
     * 收藏素材
     * @param id
     * @return
     */
    @Override
    public ResponseResult updateCollect(Integer id) {
        if (id == null || id < 0) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }

        //查询素材信息
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //判断是收藏还是取消收藏
        if (wmMaterial.getIsCollection() == 0) {
            //修改为收藏
            wmMaterial.setIsCollection((short)1); //1表示收藏
        }else {
            //取消收藏
            wmMaterial.setIsCollection((short)0); //0表示未收藏
        }

        updateById(wmMaterial);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 删除素材
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteMaterial(Integer id) {
        //校验参数
        if (id == null || id < 0) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }

        //根据id删除素材
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
